<?php
class General{
	private static $tpl = null;
	
	private static $instance = NULL;
	private $globalVars = array();
	
	
	public static function getInstance() {
		if(self::$instance === null) self::$instance = new General;
		return self::$instance;	
	}
	
	private function __construct() {}
	private function __clone() {}
	
	public function addGlobalVar($key,$value) {
		$this->globalVars[$key] = $value;
	}
	
	public function getGlobalVar($key) {
		return $this->globalVars[$key];
	}
	
	public function addAdditionalHeaderInfo($header) {
		$this->addGlobalVar("additionalHeader",$this->getGlobalVar("additionalHeader").$header);
	}
	
	
	/**
	 * Die PHP-Funktion stripslashes entfernt Quotes aus einem array mittels addslashes gequoteten String.
	 *
	 * @param array $data
	 * @return array $data
	 */
	public static function stripslashesArray($data) {
	   if (is_array($data)){
	       foreach ($data as $key => $value){
	           $data[$key] = General::stripslashesArray($value);
	       }
	       return $data;
	   } else {
	       return stripslashes($data);
	   }
	}
	
	public static function parseGlobalVars() {
		if (get_magic_quotes_gpc()) {	
			$_SERVER  = General::stripslashesArray($_SERVER);
		    $_GET     = General::stripslashesArray($_GET);
		    $_POST    = General::stripslashesArray($_POST);
		    $_COOKIE  = General::stripslashesArray($_COOKIE);
		    $_FILES   = General::stripslashesArray($_FILES);
		    $_ENV     = General::stripslashesArray($_ENV);
		    $_REQUEST = General::stripslashesArray($_REQUEST);
		}
	}
	
	
	public static function initTemplateEngine() {
		// Template
		if(!defined('SMARTY_DIR')) define('SMARTY_DIR', 'kernel/smarty/');
		require_once(SMARTY_DIR.'Smarty.class.php');
		
		General::$tpl = new Smarty;
		General::$tpl->template_dir = 'templates/'.General::getInstance()->getGlobalVar("tplFolder");
		General::$tpl->compile_dir = 'templates/'.General::getInstance()->getGlobalVar("tplFolder").'/templatesCache';
	}
	
	public static function changeTemplateFolder() {
		General::$tpl->template_dir = 'templates/'.General::getInstance()->getGlobalVar("tplFolder");
		General::$tpl->compile_dir = 'templates/'.General::getInstance()->getGlobalVar("tplFolder").'/templatesCache';
	}
	
	public static function getTpl() {
		if(!isset(General::$tpl)) {
			General::initTemplateEngine();
		}
		return General::$tpl;
	}
	
	
	public static function saveStyleFolder() {
		if(isset($_GET['s']) && isset($_GET['styleSwitcher'])) $_SESSION['styleFolder'] = $_GET['styleSwitcher'];
		if(isset($_SESSION['styleFolder']) && file_exists("templates/".$_SESSION['styleFolder'])) {
			General::getInstance()->addGlobalVar("tplFolder",$_SESSION['styleFolder']);
		}else{
			General::getInstance()->addGlobalVar("tplFolder",Settings::getInstance()->getSetting("general.defaultStyle"));
		}
	}
	
	public static function outputModuleTemplate($moduleFolder,$template) {
		if(file_exists('../../modules/'.$moduleFolder.'/templates/'.General::getInstance()->getGlobalVar("tplFolder").'/'.$template.'.html')) {
			General::getTpl()->assign('body',
				General::getTpl()->fetch('../../modules/'.$moduleFolder.'/templates/'.General::getInstance()->getGlobalVar("tplFolder").'/'.$template.'.html'));
		}else{
			General::getTpl()->assign('body',
				General::getTpl()->fetch('../../modules/'.$moduleFolder.'/templates/standard/'.$template.'.html'));
		}
	}
	
	/**
	 * Wrapper for ouputMessage (Typo)
	 */
	public static function outputMessage($msgTitle,$msgText,$tplVar = "body") {
		General::ouputMessage($msgTitle,$msgText,$tplVar);
	}
	
	
	public static function ouputMessage($msgTitle,$msgText,$tplVar = "body") {
		General::getTpl()->assign('msgTitle',$msgTitle); 
		General::getTpl()->assign('msgText',$msgText);
		
		General::getTpl()->assign($tplVar,
    		General::getTpl()->fetch('message.html'));
	}
	
	/**
	 * $unsortedArray = Array([] => id)
	 */
	public static function orderArray($unsortedArray,$dir,$idToMove) {
		$aktOrderId = null;
		foreach($unsortedArray as $orderId=>$id) {
			if($id == $idToMove) $aktOrderId = $orderId;
		}
		
		if($aktOrderId == 0 && $dir == "up") {
			return false;
		}else if($aktOrderId == (count($unsortedArray)-1) && $dir == "down") {
			return false;
		}else{
			if($dir == "up") $newOrderId = $aktOrderId-1;
			else $newOrderId = $aktOrderId+1;
			
			$temp = $unsortedArray[$aktOrderId];
			$unsortedArray[$aktOrderId] = $unsortedArray[$newOrderId];
			$unsortedArray[$newOrderId] = $temp;
		}
		return $unsortedArray;
	}
	
	public static function updateHtaccess() {
		$file = fopen("./.htaccess","w+");
		
		fwrite($file,"RewriteEngine on\n\n");
		
		foreach(Navigation::$htaccess as $key=>$value) {
			fwrite($file,"RewriteRule ^".$key."$ ".$value." [QSA]\n");
		}
		
		fclose($file);
	}
	
	
	
	
	


    /**
     * Enter description here...
     *
     * @param unknown_type $aktpage
     * @param unknown_type $proPage
     * @return unknown
     */
    public static function pages_begin($aktpage,$proPage) {
        $aktpage = (isset($aktpage)) ? $aktpage : '1';
        $min = ($aktpage - 1) * $proPage;
        $min = ($min < 1) ? 0:$min;
        return $min;
    }

    /**
     * Enter description here...
     *
     * @param unknown_type $eanz Number of Elements
     * @param unknown_type $proPage Elements per Page
     * @param unknown_type $aktpage	Current Page
     * @return unknown
     */
    public function pages_end($eanz,$proPage,$aktpage) {
        // Ausgabe: Erste Seite 1 2 [3] 4 5 Letzte Seite
        
        $output ='';
       	// Altes &seite=? entfernen
	    $url = preg_replace("/((&|\?)pages=)([0-9]{1,})/","",$_SERVER['REQUEST_URI']);
        
        if(strpos($url,"?") === false) {
        	$url .= "?pages=";
        }else{
        	$url .= "&pages=";
        }
        $url = str_replace('&','&amp;',$url);  

        $aktpage = (isset($aktpage)) ? $aktpage : '1'; 

        if($eanz <= 1) $sanz = 1;
            else $sanz = ceil($eanz / $proPage);

        
        //Erste Seite
        if ( ($aktpage != 1) )  $output .= '<a href="'.$url.'1">Erste Seite</a> ';
        else $output .= "Erste Seite ";

        if ( ($aktpage - 2) >= 1) {
            $startpage = $aktpage -2;
        } elseif ( ($aktpage - 1) >= 1) {
            $startpage = $aktpage -1;
        } else {
            $startpage = $aktpage;
        }
        
        if ( ($aktpage + 2) <= $sanz) {
            $endpage = $aktpage +2;
        } elseif ( ($aktpage + 1) <= $sanz) {
            $endpage = $aktpage +1;
        } else {
            $endpage = $aktpage;
        }

        for ($i = $startpage;$i<=$endpage;$i++) {
            if($i == $aktpage) $output .= '[<a href="'.$url.$i.'">'.$i.'</a>]&nbsp;';
            else $output .= '<a href="'.$url.$i.'">'.$i.'</a>&nbsp;';
        }

        // Letzte Seite
        if ( ($aktpage != $sanz) )  $output .= '<a href="'.$url.$sanz.'">Letzte Seite</a>';
        else $output .= "Letzte Seite";
    
        return $output;   
    }
    
    
	/**
     * Format timestamp
     *
     * @param string $timestamp Timestamp
     * @return string $datum Formatted Date (22.6.2007 - 06:43)
     */
    public static function formatDate($timestamp) {
        $datum = date("d.m.Y",$timestamp);
        $uhrzeit = date("H:i",$timestamp);
        $datum = $datum." - ".$uhrzeit;
        return $datum;
    }
    
    
 	public static function genHash($length = 10) {
        $hash = "";
        for ($i=1;$i<=$length;$i++) 
        {
            mt_srand((double)microtime()*1000000);
            $random = mt_rand(0,59);
            $hash .= substr("abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ023456789", $random, 1);
        }
        return $hash;
    }
    
    public static function getIP() {
   		if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        	$ip = getenv("HTTP_CLIENT_IP");
       	else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
           	$ip = getenv("HTTP_X_FORWARDED_FOR");
       	else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
           	$ip = getenv("REMOTE_ADDR");
       	else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
           	$ip = $_SERVER['REMOTE_ADDR'];
       	else
           	$ip = "unknown";
   		return($ip);
    }


	public static function urlExists($url) {
	    $hdrs = @get_headers($url);
	    return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$hdrs[0]) : false;
	}
}
?>